<!--  -->
<template>
  <div>
    <el-menu v-cloak :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" id="mainMenu">
      <el-menu-item index="0"
        ><font color="white">{{ listMessage }}</font></el-menu-item
      >
      <el-menu-item index="1"><font color="white">小区搜索</font></el-menu-item>
      <el-menu-item index="2"><font color="white">poi搜索</font></el-menu-item>
      <el-menu-item index="3"><font color="white">路径规划</font></el-menu-item>
      <el-menu-item index="4"><font color="white">街景联动</font></el-menu-item>
      <el-menu-item index="5"><font color="white">房价统计</font></el-menu-item>
    </el-menu>
    <component :is="componentId"></component>
  </div>
</template>

<script>
import NullComponent from './NullComponent.vue'
import Community from '../query/Community.vue'
import GeodePoi from '../query/GeodePoi.vue'
import RoutePlanning from '../query/RoutePlanning.vue'
import LinkWithStreetView from '../viewSwitching/LinkWithStreetView.vue'
import CountAveragePrice from '../statistics/CountAveragePrice.vue'

export default {
  name: 'ToolBar',
  components: { NullComponent, Community, GeodePoi, RoutePlanning, LinkWithStreetView, CountAveragePrice },
  data() {
    return {
      componentId: 'NullComponent',
      activeIndex: '0',
      componentIdArr: ['NullComponent', 'Community', 'GeodePoi', 'RoutePlanning', 'LinkWithStreetView', 'CountAveragePrice'],
      colorIndex: 0,
      arrColor: ['rgb(15,176,255)', 'rgb(18,76,154)', '#40C4E4', '#42B2BE', 'rgb(51,176,204)', '#8CB7E5', 'rgb(0,244,188)', '#139FF0'],
      lastCameraview: null,
      loading: null
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.$bus.$on('updateShowMenu', this.updateShowMenu)
    this.$bus.$on('selectMenu', this.handleSelect)
    this.$bus.$on('updatePointerEvents', this.updatePointerEvents)
  },
  computed: {
    listMessage() {
      return this.activeIndex === '0' || this.activeIndex === '3' ? '功能列表' : '收起面板'
    }
  },
  methods: {
    handleSelect(key, keyPath) {
      if (this.lastCameraview != null) {
        this.map.setCameraView(this.lastCameraview)
        this.lastCameraview = null
      }
      this.unloadDistrict()

      this.activeIndex = key

      if (!this.map.hasLayer(1001)) {
        this.map.addLayer(this.map.getLayerById(1001))
      }

      if (key === '4') {
        document.getElementById('mainMenu').style.display = 'none'
      }
      if (key === '5') {
        this.loadDistrict()
      }
      this.componentId = this.componentIdArr[key]
    },
    updateShowMenu(val) {
      this.isShowMenu = val
    },
    loadDistrict() {
      this.lastCameraview = this.map.getCameraView()

      this.map.graphicLayer.clear()
      this.map.removeLayer(this.map.getLayerById(1001))

      var that = this
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      if (!this.map.districtLayer) {
        const geoJsonLayer = new this.mars3d.layer.GeoJsonLayer({
          name: '重庆行政区',
          url: '//' + this.dataServerUrl + '/geojson/CQDistrict.json',
          symbol: {
            type: 'polygon',
            styleOptions: {
              materialType: this.mars3d.MaterialType.PolyGradient, // 重要参数，指定材质
              color: '#3388cc',
              opacity: 0.7,
              alphaPower: 1.3,
              // 面中心点，显示文字的配置
              label: {
                text: '{NAME}', // 对应的属性名称
                opacity: 1,
                font_size: 25,
                color: '#fff',
                font_family: '楷体',
                outline: false,
                scaleByDistance: true,
                scaleByDistance_far: 20000000,
                scaleByDistance_farValue: 0.1,
                scaleByDistance_near: 1000,
                scaleByDistance_nearValue: 1
              }
            },
            callback: function (attr, styleOpt) {
              return {
                color: that.getColor(that)
              }
            }
          },
          popup: `<table style="width:200px;">
                <tr><td >行政区名称：</td><td >{NAME} </td></tr>
                <tr><td >小区均价：</td><td >{AVG_PRICE}</td></tr>
              </table>`
        })
        this.map.districtLayer = geoJsonLayer
        this.map.addLayer(geoJsonLayer)

        geoJsonLayer.on(this.mars3d.EventType.load, function (event) {
          if (that.loading) {
            that.loading.close()
          }
          that.map.setCameraView({ lat: 26.482779, lng: 108.66827, alt: 629683, heading: 2, pitch: -61 })

          const options = that.getEchartsOption()
          options.clampToGround = true // 计算贴地高度

          options.pointerEvents = false

          var echartsLayer = new that.mars3d.layer.EchartsLayer(options)

          window.addEventListener('resize', function () {
            echartsLayer.resize()
          })

          // setTimeout(() => {
          if (!that.map.echartsLayer) {
            that.map.echartsLayer = echartsLayer
            that.map.addLayer(that.map.echartsLayer)
          }
          // }, 1000)
        })
      }
    },
    unloadDistrict() {
      if (this.map.districtLayer) {
        this.map.districtLayer.remove()
        this.map.districtLayer = null
      }
      if (this.map.echartsLayer) {
        this.map.echartsLayer.remove()
        this.map.echartsLayer = null
      }
    },
    getColor(that) {
      return that.arrColor[++that.colorIndex % that.arrColor.length]
    },

    updatePointerEvents(val) {
      this.map.echartsLayer.pointerEvents = val
    },
    getEchartsOption() {
      const data = [
        {
          name: '沙坪坝',
          value: 11563.6909
        },
        {
          name: '江津',
          value: 6083.9115
        },
        {
          name: '南岸',
          value: 12134.5832
        },
        {
          name: '九龙坡',
          value: 11176.0403
        },
        {
          name: '渝北',
          value: 12891.9779
        },
        {
          name: '江北',
          value: 13544.3169
        },
        {
          name: '渝中',
          value: 12702.3619
        },
        {
          name: '巴南',
          value: 9350.2041
        },
        {
          name: '北碚',
          value: 9376.9584
        },
        {
          name: '壁山',
          value: 5457.9971
        },
        {
          name: '大渡口',
          value: 10575.1372
        },
        {
          name: '长寿',
          value: 5484.4662
        },
        {
          name: '涪陵',
          value: 8542.5349
        },
        {
          name: '合川',
          value: 5697.4089
        },
        {
          name: '万州',
          value: 7013.6913
        },
        {
          name: '开州',
          value: 9121.0
        },
        {
          name: '铜梁',
          value: 6891.3165
        },
        {
          name: '垫江',
          value: 6230.3529
        },
        {
          name: '忠县',
          value: 5391.6667
        },
        {
          name: '巫山',
          value: 6119.3333
        },
        {
          name: '奉节',
          value: 6726.7857
        },
        {
          name: '荣昌',
          value: 6849.0
        },
        {
          name: '秀山',
          value: 6774.4286
        },
        {
          name: '彭水',
          value: 6607.3333
        }
      ]

      // 图表的数字从大到小向下排序
      data.sort(function (a, b) {
        return a.value - b.value
      })

      const categoryData = []
      const barData = []
      let sum = 0
      const count = data.length

      for (let i = 0; i < count; i++) {
        categoryData.push(data[i].name)
        barData.push(data[i].value)
        sum += data[i].value
      }

      const option = {
        animation: false,
        backgroundColor: 'rgba(17, 19, 42, 0.3)',
        title: [
          {
            id: 'statistic',
            text: count ? '平均: ' + parseInt((sum / count).toFixed(4)) + '元' : '',
            right: 200,
            top: 40,
            width: 100,
            textStyle: {
              color: '#fff',
              fontSize: 16
            }
          }
        ],

        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            var relVal = params.data.name + ' : ' + Math.round(params.data.value) + '元'
            return relVal
          }
        },
        grid: {
          right: 40,
          top: 100,
          bottom: 40,
          width: '30%'
        },
        xAxis: {
          type: 'value',
          scale: true,
          position: 'top',
          boundaryGap: false,
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            margin: 2,
            textStyle: {
              color: '#aaa'
            }
          }
        },
        yAxis: {
          type: 'category',
          nameGap: 16,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            interval: 0,
            textStyle: {
              color: '#ddd'
            }
          },
          data: categoryData
        },
        series: [
          {
            id: 'bar',
            zlevel: 2,
            type: 'bar',
            symbol: 'none',
            itemStyle: {
              normal: {
                color: '#ddb926'
              }
            },
            data: data
          }
        ]
      }

      return option
    }
  }
}
</script>
<style scoped>
.el-menu {
  position: absolute;
  color: #ffffff;
  top: 10px;
  left: 20px;
  background: rgba(0, 0, 0, 0.5);
  /* box-shadow: 0 3px 14px rgba(128, 128, 128, 0.5); */
  z-index: 19870100;
}

[v-cloak] {
  display: none;
}
</style>
